<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>Document</title>
  </head>
  <body>
    <canvas id="stock-canvas" width="477" height="476">
      <p>你的浏览器不支持Canvas</p>
    </canvas>
    <!-- <script>
      var canvas = document.getElementById("stock-canvas"),
        width = canvas.width,
        height = canvas.height,
        ctx = canvas.getContext("2d");
    
      console.log(data[0]);
      ctx.clearRect(0, 0, width, height);
      ctx.fillStyle = "#000000";
      ctx.fillRect(0, 0, width, height);
      ctx.fillStyle = "#FFFFFF";
      ctx.strokeStyle = "#FFFFFF";
      ctx.fillText("Test Canvas", 10, 10);
      var line = new Path2D();
      line.moveTo(10, 10);
      line.lineTo(10, canvas.height - 10);
      line.lineTo(canvas.width - 10, canvas.height - 10);
      ctx.stroke(line);
      var max =
        Math.floor(
          data.reduce(function(a, b) {
            return a.high > b.high ? a : b;
          }).high /
            100 +
            1
        ) * 100;
      var min =
        Math.floor(
          data.reduce(function(a, b) {
            return a.low < b.low ? a : b;
          }).low /
            100 -
            0
        ) * 100; //3200 - 3800
      console.log("max: " + max + " min: " + min);
      function vtoy(v) {
        return;
        canvas.height - 10 - ((v - min) * (canvas.height - 20)) / (max - min);
      }
      function dtox(d) {
        return 10 + ((canvas.width - 20) * (d + 2)) / 33;
      }
      ctx.fillText(max, 10, 20);
      ctx.fillText(min, 10, canvas.height - 10);
      data.map(function(v, d) {
        var top, bottom;
        if (v.open > v.close) {
          top = v.open;
          bottom = v.close;
          ctx.fillStyle = "#FF1111"; //ctx.strokeStyle = '#FF1111'; } else { top =
          v.close;
          bottom = v.open;
          ctx.fillStyle = "#00FF11"; //ctx.strokeStyle =
          ("#00FF11");
        }
        line.moveTo(dtox(d), vtoy(v.high));
        line.lineTo(dtox(d), vtoy(v.low));
        ctx.stroke(line);
        ctx.fillRect(dtox(d) - 3, vtoy(top), 7, vtoy(bottom) - vtoy(top));
      });
    </script> -->

    <script>
      window.loadStockData = function(r) {
        var NUMS = 90,
          data = r.data;
        if (data.length > NUMS) {
          data = data.slice(data.length - NUMS);
        }
        data = data.map(function(x) {
          return {
            date: x[0],
            open: x[1],
            close: x[2],
            high: x[3],
            low: x[4],
            vol: x[5],
            change: x[6]
          };
        });
        window.drawStock(data);
      };

      //   window.drawStock = function(data) {
      //     var canvas = document.getElementById("stock-canvas"),
      //       width = canvas.width,
      //       height = canvas.height,
      //       ctx = canvas.getContext("2d");
      //     console.log(JSON.stringify(data)); // {"date":"20150602","open":4844.7,"close":4910.53,"high":4911.57,"low":4797.55,"vol":62374809900,"change":1.69}
      //     // ctx.clearRect(0, 0, width, height);
      //     // ctx.fillText("Test Canvas", 10, 10);

      //     ctx.clearRect(0, 0, width, height);
      //     ctx.fillStyle = "black";
      //     ctx.fillText("Test Canvas", 10, 10);

      //     // 价格基准点
      //     var base_price = data[0].open;
      //     // 整K的y轴基准位置
      //     var base_y = 100;
      //     // k线图缩小比例
      //     var scale = 4;
      //     // 日K的宽度/2
      //     var single_width_half = 3;
      //     // 日K的宽度
      //     var single_width_solo = single_width_half * 2;
      //     // 日K的间隔
      //     var single_margin = 2;
      //     // 日K加间隔的宽度
      //     var single_width = single_width_solo + single_margin;

      //     for (var i in data) {
      //       // 收盘大于开盘，涨！红色。
      //       // 收盘小于开盘，跌！绿色。
      //       // 收盘等于开盘，横盘！灰色。
      //       if (data[i].close > data[i].open) {
      //         ctx.fillStyle = "red";
      //         ctx.strokeStyle = "red";
      //       } else if (data[i].close < data[i].open) {
      //         ctx.fillStyle = "green";
      //         ctx.strokeStyle = "green";
      //       } else {
      //         ctx.fillStyle = "grey";
      //         ctx.strokeStyle = "grey";
      //       }
      //       // 开/收高点
      //       var open_close_high =
      //         data[i].open > data[i].close ? data[i].open : data[i].close;
      //       // 开/收低点
      //       var open_close_low =
      //         data[i].open < data[i].close ? data[i].open : data[i].close;

      //       // 画开收矩形，开/收作为矩形的上下点
      //       var rect_start = base_y - (open_close_high - base_price) / scale;
      //       var rect_height = Math.abs(data[i].open - data[i].close) / scale;
      //       ctx.fillRect(
      //         20 + single_width * i,
      //         rect_start,
      //         single_width_solo,
      //         rect_height
      //       );

      //       // 画高直线，当高点大于开收高点，才会有高直线
      //       if (data[i].high > open_close_high) {
      //         var high_line_start = base_y - (data[i].high - base_price) / scale;
      //         var high_line_end = base_y - (open_close_high - base_price) / scale;
      //         ctx.beginPath();
      //         ctx.moveTo(
      //           20 + single_width_half + single_width * i,
      //           high_line_start
      //         );
      //         ctx.lineTo(
      //           20 + single_width_half + single_width * i,
      //           high_line_end
      //         );
      //         ctx.stroke();
      //       }

      //       // 画低直线，当低点大于开收低点，才会有低直线
      //       if (data[i].low < open_close_low) {
      //         var low_line_start =
      //           base_y - (open_close_high - base_price) / scale;
      //         var low_line_end = base_y - (data[i].low - base_price) / scale;
      //         ctx.beginPath();
      //         ctx.moveTo(
      //           20 + single_width_half + single_width * i,
      //           low_line_start
      //         );
      //         ctx.lineTo(20 + single_width_half + single_width * i, low_line_end);
      //         ctx.stroke();
      //       }
      //     }
      //   };

      window.drawStock = function(data) {
        var canvas = document.getElementById("stock-canvas"),
          width = canvas.width,
          height = canvas.height,
          ctx = canvas.getContext("2d");
        // 清空画布
        ctx.clearRect(0, 0, width, height);
        // 画上背景
        ctx.fillStyle = "#000000";
        ctx.fillRect(0, 0, width, height);
        ctx.fillStyle='#fff';
        ctx.fillText("Test Canvas", 10, 10);
        console.log("data:", data);

        // 参考别人后求最大最小值的简化方式
        var highest = data.reduce(function(x, y) {
          return x.high > y.high ? x : y;
        }).high;
        var lowest = data.reduce(function(x, y) {
          return x.low < y.low ? x : y;
        }).low;

        // 计算每个柱形的宽度的一半（避免后面循环时需要除以二）
        var everyHalfWidth = width / data.length / 2;
        // 计算数据中最高点和最低点的差值
        var heightDiff = highest - lowest;

        // 循环绘制每个柱形
        data.map((dataItem, index) => {
          // 获取某点在Canvas中的Y轴坐标
          var getRealY = function(point) {
            return ((highest - point) / heightDiff) * height;
          };

          let // 获取柱形中心X坐标
            centerX = everyHalfWidth * (index * 2 + 1),
            // 获取最高点Y坐标
            highY = getRealY(dataItem.high),
            // 获取最低点Y坐标
            lowY = getRealY(dataItem.low),
            // 获取开盘点Y坐标
            openY = getRealY(dataItem.open),
            // 获取收盘点Y坐标
            closeY = getRealY(dataItem.close);

          // 根据开盘点和收盘点的高低来判断是红色还是蓝色
          if (openY > closeY) {
            ctx.fillStyle = "#F65655";
            ctx.strokeStyle = "#F65655";
          } else {
            ctx.fillStyle = "#56F1F2";
            ctx.strokeStyle = "#56F1F2";
          }
          // 绘制柱形
          ctx.fillRect(
            centerX - everyHalfWidth,
            openY,
            everyHalfWidth * 2,
            closeY - openY
          );

          // 绘制中间线
          ctx.beginPath();
          ctx.moveTo(centerX, highY);
          ctx.lineTo(centerX, lowY);
          ctx.stroke();
        });
      };

      // 加载最近30个交易日的K线图数据:
      var js = document.createElement("script");
      js.src =
        "http://img1.money.126.net/data/hs/kline/day/history/2015/0000001.json?callback=loadStockData&t=" +
        Date.now();
      document.getElementsByTagName("head")[0].appendChild(js);
    </script>
  </body>
</html>
